<template>
  <el-dialog :title="title" :visible.sync="display" :before-close="close" top="50px">
    <el-form ref="add-form" :model="form" :inline="true" :rules="rules">
      <el-form-item label="文档标题：" prop="doc_title">
        <el-input v-model="form.doc_title" placeholder="请输入文档标题" />
      </el-form-item>
      <el-form-item style="float:right">
        <el-button type="primary" @click="sure">确 定</el-button>
        <el-button @click="close">取 消</el-button>
      </el-form-item>
    </el-form>
    <markdown-editor ref="markdownEditor" v-model="markdown" :options="{hideModeSwitch:true,previewStyle:'tab'}" height="600px" />
  </el-dialog>
</template>

<script>
import MarkdownEditor from '@/components/MarkdownEditor'
import { add, find_one_api, update } from '../api'
export default {
  components: {
    MarkdownEditor
  },
  props: {
    display: {
      type: Boolean,
      default: false
    }
  },
  data: function() {
    return {
      title: '新增文档',
      type: '',
      doc_id: '',
      doc_parent_id: '',
      form: {
        doc_title: ''
      },
      rules: {
        doc_title: [
          { required: true, message: '请输入文档标题', trigger: 'blur' }
        ]
      },
      markdown: ''
    }
  },
  methods: {
    // 如果type是修改,则查询单条服务数据,赋值显示
    find_one(doc_id) {
      find_one_api(this.$route.query.spaceid, this.$route.query.type, doc_id).then(data => {
        this.form.doc_title = data.data.doc_title
        this.doc_id = data.data.doc_id
        this.doc_parent_id = data.data.doc_parent_id
        this.markdown = data.data.doc_markdown
      })
    },
    show(type, doc_id, doc_parent_id) {
      this.type = type
      if (type === 'update') {
        this.title = '修改文档'
        this.find_one(doc_id)
      } else {
        this.title = '新增文档'
        this.form.doc_title = ''
        this.doc_id = doc_id
        this.doc_parent_id = doc_parent_id
        this.markdown = ''
      }
    },
    close() {
      this.$emit('dialog-close')
    },
    // 确定逻辑
    sure() {
      this.$refs['add-form'].validate((valid) => {
        if (valid) {
          const html = this.$refs.markdownEditor.getHtml()
          const markdown = this.$refs.markdownEditor.getValue()
          if (this.type === 'update') { // 修改文档
            update(this.doc_id, this.form.doc_title, html, markdown).then(res => {
              if (res.code === 1) {
                this.$emit('dialog-sure')
              }
            }).catch((error) => {
              console.error(error)
            })
          } else { // 添加  (同级,子级,文档)
            add(this.$route.query.spaceid, this.$route.query.type, this.doc_id, this.form.doc_title, html, markdown).then(res => {
              this.$emit('dialog-sure')
            }).catch((error) => {
              console.error(error)
            })
          }
          this.close()
        }
      })
    }
  }
}
</script>

<style lang='scss' scoped>
.api-add {
  height: 600px;
}
</style>
